﻿using AutoMapper;
using B.S.Material.Domain.Scraps;
using B.S.Material.ErrorCode;
using B.S.Material.Read.Api.Applications.Command.ProductionWasteZCommand;
using MediatR;
using SqlSugar;

namespace B.S.Material.Read.Api.Applications.Handler.ProductionWasteZHandler
{
    public class GetProductionWasteZHandler : IRequestHandler<GetProductionWasteZCommand, ApiResult<ApiPaging<ProductionWasteZ>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetProductionWasteZHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<ApiPaging<ProductionWasteZ>>> Handle(GetProductionWasteZCommand request, CancellationToken cancellationToken)
        {

            ApiResult<ApiPaging<ProductionWasteZ>> reat = new ApiResult<ApiPaging<ProductionWasteZ>>();
            var listtt = await db.Queryable<ProductionWasteZ>().Where(x => !x.IsDel).ToListAsync();
            if (!string.IsNullOrEmpty(request.DocumentSubject))
            {
                listtt = listtt.Where(x => x.DocumentSubject.Contains(request.DocumentSubject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentNumber))
            {
                listtt = listtt.Where(x => x.DocumentNumber.Contains(request.DocumentNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentMaker))
            {
                listtt = listtt.Where(x => x.DocumentMaker.Contains(request.DocumentMaker)).ToList();
            }
            if (request.WasteDate != null)
            {
                listtt = listtt.Where(x => x.WasteDate.Date == request.WasteDate.Value.Date).ToList();
            }
            int totalCount = listtt.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            listtt = listtt.OrderByDescending(a => a.ProductionWasteZID).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<ProductionWasteZ> paging = new ApiPaging<ProductionWasteZ>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = listtt.ToList(),

            };

            reat.Code = ApiEnum.显示成功;
            reat.MAG = ApiEnum.显示成功.ToString();
            reat.data = paging;
            return reat;
        }
    }
}
